package cn.wzy.service.impl;

import cn.wzy.common.CodeMsg;
import cn.wzy.common.Constant;
import cn.wzy.common.PageInfo;
import cn.wzy.common.Result;
import cn.wzy.dao.UserDao;
import cn.wzy.pojo.User;
import cn.wzy.service.UserService;

import java.util.List;
import java.util.Map;

/**
 * @author nihaowzy
 * @date 2020/12/22 17:12
 */
public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDao();

    @Override
    public Result queryUserByUsernameAndPassword(String username, String password) throws Exception {
        User user = userDao.SelectUserByUsernameAndPassWord(username, password);
        //校验用户是否存在，不存在说明用户名和密码错误
        if (null == user ){
            return new Result(CodeMsg.USER_NAME_PASSWORD_ERROR);
        }
        //判断用户是否是离职，如果是离职的话就不能登录
        if (user.getDeleted().equals(Constant.USER_DELETE)){
            return new Result(CodeMsg.USER_DELETED_ERROR);
        }
        //将用户信息 放入到Result中是为了 在servlet中放入session中
        return new Result(user);
    }

    @Override
    public Result queryPage(Map<String, String> params, Integer page, Integer limit) throws Exception {
        PageInfo<User> userPageInfo = userDao.selectPage(params, page, limit);

        return new Result(userPageInfo);
    }

    @Override
    public Result resetPassword(String id) throws Exception {
         userDao.resetPwd(id,Constant.ORI_PASSWORD);
        return new Result();
    }

    @Override
    public Result deleted(String id) throws Exception {
        userDao.del(id,Constant.USER_DELETE);
        return new Result();
    }

    @Override
    public Result addUser(String username, String realname, Integer role) throws Exception {
        User user = userDao.selectUserByRealname(realname);
        //校验用户是否存在
        if (user != null){
            return new Result(CodeMsg.USER_IS_EXIST);
        }
        userDao.add(realname,username,Constant.ORI_PASSWORD,role,Constant.USER_DELETE_NOT);
        return new Result();
    }

    @Override
    public Result queryUser() throws Exception {
        List<User> userList =  userDao.selectByDeletedAndRole(Constant.USER_DELETE_NOT,Constant.USER_ROLE_SALESMAN);
        return new Result(userList);
    }

    @Override
    public Result updatePassword(Integer id, String newPassword) throws Exception {
        userDao.updatePassword(id,newPassword);

        return  new Result();
    }

    @Override
    public Result upLoadImg(Integer id, String imgUrl) throws Exception {
        userDao.uploadImg(id,imgUrl);

        return new Result(imgUrl);
    }
}
